package com.example.mvvmdemo.data.network;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public abstract class BaseRetrofit<T> {

    private static final String DATE_FORMAT = "yyyy-MM-dd'T'hh:mm:ssZ";

    private T networkService;

    private void initNetworkInterface() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = okHttpClientHandler(new OkHttpClient.Builder())
            .addInterceptor(loggingInterceptor).build();
        Gson gson = gsonHandler(new GsonBuilder().setPrettyPrinting())
            .setDateFormat(DATE_FORMAT).create();
        Retrofit.Builder retrofitBuilder = new Retrofit.Builder().baseUrl(getBaseUrl());
        Retrofit retrofit = retrofitHandler(retrofitBuilder)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(gson)).client(client).build();
        this.networkService = retrofit.create(getRestClass());
    }

    protected T getNetworkService() {
        if (this.networkService == null) {
            initNetworkInterface();
        }
        return this.networkService;
    }

    private Retrofit.Builder retrofitHandler(Retrofit.Builder builder) {
        return builder;
    }

    OkHttpClient.Builder okHttpClientHandler(OkHttpClient.Builder builder) {
        return builder;
    }

    private GsonBuilder gsonHandler(GsonBuilder builder) {
        return builder;
    }

    protected abstract String getBaseUrl();

    protected abstract Class<T> getRestClass();
}
